from pathlib import Path 
import shutil 
from datetime import datetime 
import logging 
import os 

from .error import Missing 
from .config import get_settings
from .database import create_curs 
from .alter_file_name import get_path 

logger = logging.getLogger(__name__)

settings = get_settings()
ROOT_DIR = settings.root_dir
CREATE_ROOT_DIR_NAME = settings.create_root_dir_name
SQL = settings.sql 



def find(files: list[str]) -> list[Path] : 
    
    p = get_path() 
    if not p: 
        raise Missing('源文件不存在')
    
    lis = []
    for f in files: 
        res = list(p.rglob(f))
        if not res: 
            logger.info('文件 %s 缺失\n', f)
            continue
        for r in res: 
            lis.append(r)

    return lis 
   

def copy_file(root_path: Path, file_names: list) -> None: 
    files = find(file_names) 
    
    if not any(files): 
        logger.info('没有查到到任何商品\n') 
        
        return 
    
    for f in files: 

        shutil.copytree(f, root_path /f.stem, dirs_exist_ok=True)
        logger.info('商品: %s 复制成功\n', f.stem)
    

def get_names() -> list[str] : 
    names: list = []
    args = os.getenv('names')
    if args:
        names = args.split(',')
        return names 
    

    with create_curs() as curs: 
        curs.execute(SQL) 
        rows = curs.fetchall() 
    if not rows: 
        raise Missing('没有查到到任何商品')
    
    for r in rows: 
        names.append(r[0])

    logger.info('需要复制的商品名称：%s\n', ','.join(names))
    return names 


def main(): 
    # 创建根目录
    root = Path(__file__).parents[1] / CREATE_ROOT_DIR_NAME
    root.mkdir(exist_ok=True)

    # 创建子目录
    child_dir = root / str(datetime.today()).replace(' ', '').replace(':', '').replace('.', '-')
    child_dir.mkdir(exist_ok=True)

    filename = child_dir / 'input.log'
    logging.basicConfig(filename=filename, encoding='utf-8', level=logging.INFO)

    names = get_names()

    copy_file(child_dir, names)


if __name__ == '__main__': 

    main()